package com.anyou.mall.supply.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.collection.CollUtil;
import com.anyou.common.exception.ServiceException;
import com.anyou.common.utils.DateUtils;
import com.anyou.common.utils.SnowFlakeUtils;
import com.anyou.mall.order.domain.OrdOrder;
import com.anyou.mall.order.mapper.OrdOrderMapper;
import com.anyou.mall.order.service.IOrdOrderService;
import com.anyou.mall.pla.service.impl.BannerServiceImpl;
import com.anyou.mall.sho.domain.CarPartsShop;
import com.anyou.mall.sho.mapper.CarPartsShopMapper;
import com.anyou.mall.supply.domain.SupplyTime;
import com.anyou.mall.supply.mapper.SupplyTimeMapper;
import com.anyou.mall.supply.service.ISupplyTimeService;
import com.anyou.mall.supply.vo.GoodsVo;
import com.anyou.mall.supply.vo.SupplyVo;
import com.anyou.mall.util.AssertUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.anyou.mall.supply.mapper.SupplyMapper;
import com.anyou.mall.supply.domain.Supply;
import com.anyou.mall.supply.service.ISupplyService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 补给单Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-13
 */
@Service
public class SupplyServiceImpl  implements ISupplyService
{
    @Autowired
    private SupplyMapper supplyMapper;
    @Autowired
    private SupplyTimeMapper supplyTimeMapper;
    @Autowired
    private CarPartsShopMapper carPartsShopMapper;
    @Autowired
    private OrdOrderMapper ordOrderMapper;

    @Autowired
    private IOrdOrderService orderService;
    @Autowired
    private ISupplyTimeService supplyTimeService;
    /**
     * 查询补给单
     *
     * @param supplyId 补给单主键
     * @return 补给单
     */
    @Override
    public SupplyVo selectSupplyBySupplyId(Long supplyId)
    {
        SupplyVo supplyVo = supplyMapper.selectSupplyBySupplyId(supplyId);
        AssertUtils.isNull(supplyVo,"补给订单不存在");
        //查询商品信息
        GoodsVo goodVo=supplyMapper.selectGoodsByGoodsSkuId(supplyVo.getGoodSkuId());
       if(goodVo!=null){
           supplyVo.setGoodsVo(goodVo);
       }

        //查询配送时间
        List<SupplyTime> supplyTimes = supplyTimeMapper.selectList(new LambdaQueryWrapper<SupplyTime>()
                .eq(SupplyTime::getSupplyId, supplyVo.getSupplyId()));
        if(CollUtil.isNotEmpty(supplyTimes)){
            supplyVo.setSupplyTimeList(supplyTimes);
        }

        return supplyVo;
    }

    /**
     * 查询补给单列表
     *
     * @param supply 补给单
     * @return 补给单
     */
    @Override
    public List<Supply> selectSupplyList(Supply supply)
    {
        return supplyMapper.selectSupplyList(supply);
    }

    /**
     * 新增补给单
     *
     * @param supply 补给单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertSupply(Supply supply)
    {
        supply.setCreateTime(DateUtils.getNowDate());
        supply.setNextDeliveryTime(supply.getStartTime());
        //查看当前街道是否有合伙人
        List<CarPartsShop> partnerList = carPartsShopMapper.selectList(new LambdaQueryWrapper<CarPartsShop>()
                .eq(CarPartsShop::getPartnerProvince, supply.getReceiveProvince())
                .eq(CarPartsShop::getPartnerCity, supply.getReceiveCity())
                .eq(CarPartsShop::getPartnerArea, supply.getReceiveArea())
                .eq(CarPartsShop::getPartnerStreet, supply.getReceiveStreet()));
        if(CollUtil.isNotEmpty(partnerList)){
            supply.setPartnerId(partnerList.get(0).getCarPartsShopId());
        }
        int i = supplyMapper.insert(supply);
        //余数
       int yu= supply.getTotalNum()%supply.getEveryNum();
       //送几次
        int times=supply.getTotalNum()/supply.getEveryNum();
        if(yu>0){
            times=times+1;
        }
        supply.setTotalTime(times);
        if(i>0){
            LocalDate psTime=supply.getStartTime();
            int price=supply.getGoodsTotalPrice().intValue()/times;
            int totalPrice=price*times;
            //新增配送时间
            for (int j = 1; j <=times ; j++) {
                SupplyTime supplyTime = new SupplyTime();
                supplyTime.setSupplyId(supply.getSupplyId());
                //配送时间
                supplyTime.setPsTime(psTime);
                //第几次配送
                supplyTime.setTimesNum(j);
                //配送状态（0-待配送，1-配送中，2-已完成）
                supplyTime.setSupplyStatus(0);
                //当前次配送数量
                supplyTime.setPsNum(supply.getEveryNum());
                supplyTime.setGoodsPrice(supply.getGoodsTotalPrice().subtract(new BigDecimal(totalPrice)));
                if(j==times&&yu>0){
                    //如果是最后一次，并且余数不为0
                    supplyTime.setPsNum(yu);
                }
                supplyTimeMapper.insert(supplyTime);
                //如果配送时间与当前日期相同，就立马生成一个订单到order表中
                if(DateUtils.getDate().equals(DateUtils.getStringByDate(psTime))){
                    //执行一次创建补给定单的定时方法
                    this.ceateBjOrderTask();
                }
                psTime=psTime.plusDays(supply.getIntervalDate());

            }
        }

        return 1;
    }

    /**
     * 修改补给单
     *
     * @param supply 补给单
     * @return 结果
     */
    @Override
    public int updateSupply(Supply supply)
    {
        supply.setUpdateTime(DateUtils.getNowDate());
        return supplyMapper.updateSupply(supply);
    }

    /**
     * 批量删除补给单
     *
     * @param supplyIds 需要删除的补给单主键
     * @return 结果
     */
    @Override
    public int deleteSupplyBySupplyIds(Long[] supplyIds)
    {
        return supplyMapper.deleteSupplyBySupplyIds(supplyIds);
    }

    /**
     * 删除补给单信息
     *
     * @param supplyId 补给单主键
     * @return 结果
     */
    @Override
    public int deleteSupplyBySupplyId(Long supplyId)
    {
        return supplyMapper.deleteSupplyBySupplyId(supplyId);
    }

    /**
     * 定时生成补给订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void ceateBjOrderTask() {
        List<Supply> supplies = supplyMapper.selectList(new LambdaQueryWrapper<Supply>()
                .eq(Supply::getFinishStatus, 0));
        //当前日期
        String nowdate = DateUtils.getDate();
        //要添加的订单列表
        List<OrdOrder> orders = new ArrayList<OrdOrder>();
        //要修改已生成订单状态的配送时间记录列表
        List<SupplyTime> stList = new ArrayList<SupplyTime>();
        supplies.forEach(sup->{
            //查询未生成订单的配送时间
            List<SupplyTime> supplyTimes = supplyTimeMapper.selectList(new LambdaQueryWrapper<SupplyTime>()
                    .eq(SupplyTime::getSupplyId, sup.getSupplyId())
                    .eq(SupplyTime::getAddOrder, 0));
            supplyTimes.forEach(supTime -> {
                //配送时间
                String psTime = DateUtils.getStringByDate(supTime.getPsTime());
                if(nowdate.equals(psTime)){
                    //通过补给订单创建订单
                    OrdOrder order= creatOrderBySuply(sup,supTime);
                    orders.add(order);
                    supTime.setAddOrder(1);
                    stList.add(supTime);
                }
            });
        });
        if(CollUtil.isNotEmpty(orders)){
            orderService.saveBatch(orders);
            supplyTimeService.updateBatchById(stList);
        }

    }
    /**
     * 修改下次配送时间
     * @param date
     */
    @Override
    public void editTime(LocalDate date) {
        List<SupplyTime> list = supplyTimeService.list(new LambdaQueryWrapper<SupplyTime>()
                .ge(SupplyTime::getPsTime, LocalDate.now())
                .orderByAsc(SupplyTime::getPsTime)
        );
        if(CollUtil.isNotEmpty(list)){
            SupplyTime supplyTime = list.get(0);
            supplyTime.setPsTime(date);
            supplyTimeMapper.updateById(supplyTime);
        }

    }

    /**
     * 开始配送
     * @param supplyId
     */
    @Override
    public void startPs(Long supplyId) {
        Supply supply = supplyMapper.selectById(supplyId);
        if(supply != null){
            //查询当天的配送时间
            SupplyTime st = supplyTimeMapper.selectOne(new LambdaQueryWrapper<SupplyTime>()
                    .eq(SupplyTime::getSupplyId, supplyId)
                    .eq(SupplyTime::getPsTime, LocalDate.now()));
            if(st!=null){
                //查询订单中是否有当前补给时间id的补给订单
                OrdOrder order = ordOrderMapper.selectOne(
                        new LambdaQueryWrapper<OrdOrder>()
                                .eq(OrdOrder::getSupplyTimeId, st.getSupplyTimeId()));
                if(order==null){
                    //新增订单
                    OrdOrder ordOrder = creatOrderBySuply(supply, st);
                    ordOrderMapper.insert(ordOrder);
                }

            }
        }


    }

    /**
     * 判断所属合伙人
     * @param receiveProvince
     * @param receiveCity
     * @param receiveArea
     * @param receiveStreet
     * @return
     */
    @Override
    public Long getPartnerId(String receiveProvince, String receiveCity, String receiveArea, String receiveStreet) {
        //查找当前区域的合伙人
        CarPartsShop one = carPartsShopMapper.selectOne(new LambdaQueryWrapper<CarPartsShop>()
                .eq(CarPartsShop::getPartnerProvince, receiveProvince)
                .eq(CarPartsShop::getPartnerCity, receiveCity)
                .eq(CarPartsShop::getPartnerArea, receiveArea)
                .eq(CarPartsShop::getPartnerStreet, receiveStreet));
        if(one!=null){
           return one.getCarPartsShopId();
        }
        return 0L;
    }

    /**
     * 通过补给订单创建订单
     * @param sup
     * @param supTime
     * @return
     */
    private OrdOrder creatOrderBySuply(Supply sup, SupplyTime supTime) {
        OrdOrder order = new OrdOrder();
        order.setSupplyId(sup.getSupplyId());
        order.setOrderType(2);
        order.setOrderNo(SnowFlakeUtils.nextId()+"");
        order.setGoodsNumber(supTime.getPsNum());
        order.setPayMode("2");
        order.setIsPay("1");
        order.setOrderStatus("2");
        order.setOrderAmount(supTime.getGoodsPrice());
        order.setGoodsAmount(supTime.getGoodsPrice());
        order.setDiscountAmount(new BigDecimal("0"));
        order.setDeliveryTime(DateUtils.getStringByDate(supTime.getPsTime()));
        order.setReceiverName(sup.getReceiveName());
        order.setReceiverPhone(sup.getReceivePhone());
        order.setReceiverProvince(sup.getReceiveProvince());
        order.setReceiverCity(sup.getReceiveCity());
        order.setReceiverArea(sup.getReceiveArea());
        order.setReceiverStreet(sup.getReceiveStreet());
        order.setReceiverDetailed(sup.getReceiveAddr());
        order.setSupplyTimeId(supTime.getSupplyTimeId());
        //判断所属合伙人
        Long partnerId = this.getPartnerId(sup.getReceiveProvince(),sup.getReceiveCity(),sup.getReceiveArea(),sup.getReceiveStreet());
        order.setCarPartsShopId(partnerId);
        return order;

    }
}
